package com.exam.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName LogAop
 * @Description 日志切面 记录各个接口的调用情况等
 * 项目可优化点
 * 1、考试结束后，一键退出 不卡在原页面
 * 2、考试期间防止切屏 切屏警告 摄像头
 * 3、成绩分析更加直观一点 柱状图 折线图等
 * @Author 周轩霆
 **/
@Slf4j
@Aspect
@Component
public class LogAop {
    //slfj日志
    private static Logger logger = LoggerFactory.getLogger(LogAop.class);

    /**
     * 切点
     */
    @Pointcut("execution(public *  com.exam.controller..*.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object logHelper(ProceedingJoinPoint pjp) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        assert sra != null;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String className = pjp.getSignature().getDeclaringTypeName();
        String methodName = pjp.getSignature().getName();
        long startTime = System.currentTimeMillis();
        Object rs = null;
        boolean successAble = false;
        Object[] params = pjp.getArgs();
      /*  JSONObject paramsJson = null;
        if (params.length == 1 && !(params[0] instanceof Integer)) {
            //防止参数为0的参数报错
            paramsJson = (JSONObject) JSONObject.toJSON(params[0]);
        }*/
        try {
            rs = pjp.proceed();
            successAble = true;
            logger.info("{请求url:{}, 请求方式:{}, 是否成功执行:{}, 耗时:{}ms, 请求参数:{},接口所在类:{},请求接口:{}}", url, method, successAble, System.currentTimeMillis() - startTime, JSON.toJSONString(params),className,methodName);
            return rs;
        } catch (Throwable e) {
            logger.error("{系统错误:{} ,请求url:{}, 请求方式:{}, 是否成功执行:{}, 耗时:{}ms, 请求参数:{},接口所在类:{},请求接口:{}}", e, url, method, successAble, System.currentTimeMillis() - startTime, JSON.toJSONString(params),className,methodName);
            return rs;
        }
    }
}
